/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.core;

import com.alee.managers.settings.SettingsManager;
import com.alee.utils.ImageUtils;
import com.rag.managers.UsersManager;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.net.URL;

/**
 * User: mgarin Date: 09.06.12 Time: 19:58
 */

@XStreamAlias( "PostData" )
public class PostData implements Serializable
{
    @XStreamAsAttribute
    private String userId;

    @XStreamAsAttribute
    private Long date;

    @XStreamAsAttribute
    private String avatarUrl;
    private transient ImageIcon avatar;
    private transient int avatarSize = -1;

    @XStreamAsAttribute
    private String message;

    public PostData ()
    {
        super ();
    }

    public String getUserId ()
    {
        return userId;
    }

    public void setUserId ( String userId )
    {
        this.userId = userId;
    }

    public Long getDate ()
    {
        return date;
    }

    public void setDate ( Long date )
    {
        this.date = date;
    }

    public String getAvatarUrl ()
    {
        return avatarUrl;
    }

    public void setAvatarUrl ( String avatarUrl )
    {
        this.avatarUrl = avatarUrl;
    }

    public String getMessage ()
    {
        return message;
    }

    public void setMessage ( String message )
    {
        this.message = message;
    }

    /**
     * Дополнительные методы
     */

    public User getAuthor ()
    {
        return UsersManager.getUser ( userId );
    }

    public ImageIcon getAvatar ()
    {
        // Получаем желаемый размер аватарки
        int avatarSize = SettingsManager.getInteger ( "Post.avatarSize", 48 );

        // Создаём аватарку
        if ( avatar == null || this.avatarSize != avatarSize )
        {
            // Запоминаем последний сгенерированный размер
            this.avatarSize = avatarSize;

            try
            {
                // Загружаем аватарку
                avatar = ImageUtils.loadImage ( new URL ( avatarUrl ) );

                // Сайзим аватарку, если она больше желаемого размера
                if ( avatar.getIconWidth () > avatarSize || avatar.getIconHeight () > avatarSize )
                {
                    avatar = ImageUtils.createPreviewIcon ( avatar, avatarSize );
                }

                // Уравниваем ширину и высоту аватарки
                avatar = ImageUtils.resizeCanvas ( avatar, avatarSize, avatarSize );

                // Заполняем фон аватарки
                avatar = ImageUtils.addBackground ( avatar, Color.WHITE );
            }
            catch ( Throwable e )
            {
                // Используем дефолтную аватарку
                avatar = getDefaultAvatar ( avatarSize );
            }
        }

        return avatar;
    }

    private static transient ImageIcon defaultAvatar = null;
    private static transient int defaultAvatarSize = -1;
    private static transient Color defaultAvatarColor = new Color ( 220, 220, 220 );

    private static ImageIcon getDefaultAvatar ( int avatarSize )
    {
        if ( defaultAvatar == null || defaultAvatarSize != avatarSize )
        {
            // Запоминаем новый размер
            defaultAvatarSize = avatarSize;

            // Создаём новое изображение
            BufferedImage bi =
                    new BufferedImage ( avatarSize, avatarSize, BufferedImage.TYPE_INT_ARGB );
            Graphics2D g2d = bi.createGraphics ();
            g2d.setPaint ( new GradientPaint ( 0, 0, Color.WHITE, avatarSize, avatarSize,
                    defaultAvatarColor ) );
            g2d.fillRect ( 0, 0, avatarSize, avatarSize );
            g2d.dispose ();

            defaultAvatar = new ImageIcon ( bi );
        }
        return defaultAvatar;
    }
}